package com.bincloud.vue.admin.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring 工具类
 * @author bincloud, mvpzhou
 */
@Component
@SuppressWarnings("unused")
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {

    private SpringUtils(){}

    private static ConfigurableListableBeanFactory beanFactory;

    private static ApplicationContext applicationContext;

    @Override
    public synchronized void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringUtils.beanFactory = beanFactory;
    }

    @Override
    public synchronized void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) beanFactory.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> clazz) throws BeansException {
        return beanFactory.getBean(name, clazz);
    }

    public static boolean containsBean(String name) {
        return beanFactory.containsBean(name);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBeanBy(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBeanBy(String name, Class<T> clazz) throws BeansException {
        return applicationContext.getBean(name, clazz);
    }

    public static boolean containsBeanBy(String name) {
        return applicationContext.containsBean(name);
    }

}
